package com.wanghengzhi.kata;

import java.util.*;

/**
 * @author wanghengzhi
 * @since 2021/11/20 13:06
 */
public class Anagrams {

    public Set<String> generate(String word) {
        if (word.length() == 1) {
            return Collections.singleton(word);
        }
        Set<String> anagrams = new HashSet<>();
        for (int index = 0; index < word.length(); index++) {
            char firstCharOfAnagrams = word.charAt(index);
            String otherCharsExcludeFirstChar = removeCharAt(word, index);
            Set<String> combinationsOfOtherChars = generate(otherCharsExcludeFirstChar);
            for (String oneCombination : combinationsOfOtherChars) {
                anagrams.add(firstCharOfAnagrams + oneCombination);
            }
        }
        return anagrams;
    }

    private String removeCharAt(String word, int index) {
        return new StringBuilder(word).deleteCharAt(index).toString();
    }

}
